package com.heima.wemedia.scan.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.AliyunGreenTemplate;
import com.heima.feign.api.ApArticleFeignCient;
import com.heima.file.MinIOTemplate;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.entity.WmChannel;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.utils.common.SnowflakeIdWorker;
import com.heima.wemedia.dao.WmChannelDao;
import com.heima.wemedia.dao.WmNewsDao;
import com.heima.wemedia.dao.WmUserDao;

import com.heima.wemedia.scan.dao.WmSensitiveDao;
import com.heima.wemedia.scan.service.WmNewsAutoScanService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Resource
    private WmNewsDao wmNewsDao;

    @Resource
    private WmUserDao wmUserDao;

    @Resource
    private WmChannelDao wmChannelDao;

    @Resource
    private MinIOTemplate minIOTemplate;

    @Resource
    private AliyunGreenTemplate aliyunGreenTemplate;

    @Resource
    private WmSensitiveDao wmSensitiveDao;

    @Resource
    private ApArticleFeignCient apArticleFeignCient;

    @Override
    public void autoScanNews(Long newsId) {
        //1. 查询文章详情, 判断文章是否存在
        WmNews wmNews = wmNewsDao.queryById(newsId);
        if (wmNews == null) {
            throw new RuntimeException("文章数据不存在");
        }

        //状态判断 ---- 不是待审核, 直接返回
        if (wmNews.getStatus() != 1) {
            return;
        }

        //2. 抽取文章文本内容和图片数据
        Map<String, Object> textAndImages = extractTextAndImages(wmNews);

        //3. 内容审核
        String text = (String) textAndImages.get("text");

        //3.0 敏感词审核-------------------------------
        boolean sensitiveScan = handleSensitiveScan(wmNews, text);
        if (!sensitiveScan) {
            return;
        }

        //3.1 文本审核

        boolean textScan = handleTextScan(wmNews, text);
        if (!textScan) {
            return;
        }
        //3.2 图片审核
        List<String> images = (List<String>) textAndImages.get("images");
        boolean imagesScan = handleImagesScan(wmNews, images);
        if (!imagesScan) {
            return;
        }

        //4. 审核通过, 修改文章状态
        if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
            updateStatus(wmNews, 8, "审核通过");
            return;
        }

        //4.2 如果已经到了用户设置的发布时间, 需要修改文章状态为9 , 并且发布文章
        saveArticle(wmNews);
    }

    /**
     * 审核通过发布文章
     *
     * @param wmNews
     */
   public void saveArticle(WmNews wmNews) {
        //1. 封装参数
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, articleDto);

        //处理数据  id  authorId authorName  channelName  layout
        articleDto.setNewsId(wmNews.getId());

        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserDao.queryById(Math.toIntExact(wmNews.getUserId()));
        if (wmUser != null) {
            articleDto.setAuthorName(wmUser.getNickname());
        }

        WmChannel wmChannel = wmChannelDao.queryById(wmNews.getChannelId());
        if (wmChannel != null) {
            articleDto.setChannelName(wmChannel.getName());
        }

        articleDto.setLayout(wmNews.getType().intValue());

        //2. 调用文章服务发布文章
        ResponseResult responseResult = apArticleFeignCient.saveArticle(articleDto);
        if (responseResult.getCode()==200) {
            //3. 修改文章状态为已发布
            updateStatus(wmNews,9,"文章已发布");
        }

    }

    /**
     * 敏感词审核
     *
     * @param wmNews
     * @param text
     * @return
     */
    private boolean handleSensitiveScan(WmNews wmNews, String text) {
        //1. 判断审核文本是否为空
        if (StringUtils.isBlank(text)) {
            return true;
        }


        //3. 进行敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);
        if (result.size() > 0) {
            updateStatus(wmNews,  2, "文本或图片内容中包含敏感词");
            return false;
        }

        return true;
    }

    /**
     * 图片审核
     *
     * @param wmNews
     * @param images
     * @return
     */
    private boolean handleImagesScan(WmNews wmNews, List<String> images) {
        //1. 判断图片是否存在
        if (CollectionUtils.isEmpty(images)) {
            return true;
        }
        try {
            //2. 下载图片字节
            List<byte[]> list = images.stream().map(image -> minIOTemplate.downLoadFile(image)).collect(Collectors.toList());

            //3. 调用阿里云审核图片  pass block review
            Map<String, String> result = aliyunGreenTemplate.greenImageScan(list);

            //审核失败, 图片中包含违规信息
            if ("block".equals(result.get("suggestion"))) {
                updateStatus(wmNews,  2, "图片内容中包含违规信息");
                return false;
            }
            //需要进行人工审核
            if ("review".equals(result.get("suggestion"))) {
                updateStatus(wmNews,  3, "图片中包含不确定信息");
                return false;
            }

            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
            updateStatus(wmNews,  3, "阿里云图片审核失败:" + exception.getMessage());
            return false;
        }
    }

    /**
     * 文本审核
     *
     * @param wmNews
     * @param text
     * @return
     */
    private boolean handleTextScan(WmNews wmNews, String text) {
        if (StringUtils.isBlank(text)) {
            return true;
        }
        try {
            //使用阿里云进行文本审核  pass    review
            Map<String, String> result = aliyunGreenTemplate.greenTextScan(text);
            //审核失败, 内容中包含违规信息
            if ("block".equals(result.get("suggestion"))) {
                updateStatus(wmNews, 2, "文章内容中包含违规信息");
                return false;
            }
            //需要进行人工审核
            if ("review".equals(result.get("suggestion"))) {
                updateStatus(wmNews,  3, "文章内容中包含不确定信息");
                return false;
            }

            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
            updateStatus(wmNews,  3, "阿里云文本审核失败:" + exception.getMessage());
            return false;
        }
    }

    private void updateStatus(WmNews wmNews, Integer status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wmNewsDao.update(wmNews);
    }

    /**
     * 抽取文本和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> extractTextAndImages(WmNews wmNews) {
        //1. 抽取文章内容中的图片和文本
        String content = wmNews.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);

        StringBuilder text = new StringBuilder();
        List<String> images = new ArrayList<>();

        for (Map map : list) {
            //图片数据
            if ("image".equals(map.get("type"))) {
                images.add((String) map.get("value"));
            }

            //文本数据
            if ("text".equals(map.get("type"))) {
                text.append(map.get("value") + ",");
            }
        }

        //2. 抽取标题文本和封面图片
        text.append(wmNews.getTitle());

        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("text", text.toString());
        result.put("images", images);

        return result;
    }
}